﻿using Nancy;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NancySwagger
{
    public class SwaggerModule : NancyModule
    {
        public SwaggerModule()
        {
            //全局静态资源
            Get("/swagger", RedirectToIndex);
            Get("/swagger/index.html", Index);
            Get("/swagger/{name*}", StaticResource);
        }

        private object RedirectToIndex(dynamic dynamic)
        {
            return Response.AsRedirect("/swagger/index.html");
        }

        private object Index(dynamic dynamic)
        {
            var url = $"{Request.Url.BasePath}/api-docs";
            string packUri = $"NancySwagger.Resources.SwaggerUI.index.html";
            string contentType = MimeTypes.GetMimeType(Path.GetExtension(packUri));
            byte[] bytes = null;
            using (var stream = typeof(SwaggerModule).Assembly.GetManifestResourceStream(packUri))
            {
                bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
            }
            string html = Encoding.UTF8.GetString(bytes);
            html = html.Replace("@url", url);
            return Response.AsText(html, contentType);
        }

        private object StaticResource(dynamic dynamic)
        {
            string name = dynamic.name;
            return Resouce(name);
        }

        private object Resouce(string resourcePath)
        {
            if (resourcePath == "")
                resourcePath = "index.html";
            string packUri = $"NancySwagger.Resources.SwaggerUI.{resourcePath.Replace("/", ".")}";
            string contentType = MimeTypes.GetMimeType(Path.GetExtension(packUri));
            return Response.FromStream(typeof(SwaggerModule).Assembly.GetManifestResourceStream(packUri), contentType);
        }
    }
}
